﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gin.Commands;
using Gin.Util.TarArchiver;
using System.IO;

namespace Gin
{
    public class PackageContent
    {

        Dictionary<string, string> _fileMap;

        private string _packageContentDirectory;

        public PackageContent(string packageContentDirectory, string packageResultFilePath)
        {
            _packageContentDirectory = packageContentDirectory;
            _fileMap = new Dictionary<string, string>();

            using (FileStream unarchFile = File.OpenRead(packageResultFilePath))
            {
                TarReader reader = new TarReader(unarchFile);
                reader.ReadToEnd(packageContentDirectory);
            }
        }

        public PackageContent() 
        {
            _fileMap = new Dictionary<string, string>();
        }

        public bool ContainFilePath(string filePath)
        {
            return _fileMap.ContainsKey(filePath);
        }

        public bool ContainFileName(string fileName)
        {
            return _fileMap.ContainsValue(fileName);
        }

        public void AddContent(string sourcePath, string destFileName)
        {
            _fileMap.Add(sourcePath, destFileName);
        }

        public void SaveAs(string resultFilePath)
        {
            using (FileStream archUsTar = File.Create(resultFilePath))
            {
                using (TarWriter legacyTar = new TarWriter(archUsTar))
                {
                    foreach (var file in _fileMap)
                    {
                        string destFileName = file.Value;
                        string sourceFilePath = file.Key;

                        using (FileStream sourceFileStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
                        {
                            legacyTar.Write(sourceFileStream, sourceFileStream.Length, destFileName);
                        }
                    }
                }
            }
        }

        public string GetFileName(string sourcePath)
        {
            return _fileMap[sourcePath];
        }

        public string GetFilePath(string fileName)
        {
            return _fileMap.FirstOrDefault(f => f.Value == fileName).Key;
        }

        public string GetContent(string fileName)
        {
            return Path.Combine(_packageContentDirectory, fileName);
        }
    }
}
